package com.freestyle.common.support;

import com.freestyle.common.models.JSONData;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;

/**
 * Created by rocklee on 2021/12/16 16:14
 */
@Configuration
public class AppEvent implements ApplicationListener<ContextRefreshedEvent> {
  private MyResponseBodyAdvice.OnAdvice onAdvice= new MyResponseBodyAdvice.OnAdvice() {
    private ThreadLocal<Object> mBody = new ThreadLocal<Object>();

    @Override
    public boolean OnAdvice(Object body, boolean isResponseBody, boolean isFromAjax, MediaType selectedContentType, ServerHttpRequest request, ServerHttpResponse response) {
      if (!isResponseBody || !isFromAjax) {
        mBody.set(body);
        return true;
      }
      return false;
    }

    @Override
    public Object get() {
      return mBody.get();
    }

    public Boolean call() throws Exception {
      return null;
    }
  };

    @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
      MyResponseBodyAdvice.addToAdvice(onAdvice);
  }
}
